package com.dahuyou.io.model.aio.client;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.util.concurrent.Future;

public class AioClient {

    public static void main(String[] args) throws Exception {
        AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open();
//        Future<Void> future = socketChannel.connect(new InetSocketAddress("127.0.0.1", 7397));
//        socketChannel.connect(new InetSocketAddress("127.0.0.1", 7397));
        // aio的a体现：指定一个回调类，建立连接成功时回调
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 7397), null, new CompletionHandler<Void, Object>() {
            @Override
            public void completed(Void result, Object attachment) {
                System.out.println("connect to nio server suc!");
                ByteBuffer allocate = ByteBuffer.allocate(1024);
                socketChannel.read(allocate, allocate, new AioClientHandler(socketChannel, Charset.forName("GBK")));

            }

            @Override
            public void failed(Throwable exc, Object attachment) {

            }
        });

        System.out.println("dahuyou-study-netty aio client start done.");
//        future.get();
        // 读数据
        // clientChannel.read(readBuffer, readBuffer, new ReadHandler(clientChannel, latch));
//        socketChannel.read(ByteBuffer.allocate(1024), null, new AioClientHandler(socketChannel, Charset.forName("GBK")));
        Thread.sleep(10000000);
    }

}
